package com.lonely.fx.list_view;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * @date: 2022-07-29 11:08
 * @author: ztkj-hzb
 * @description: 基于定制化的 ListView
 **/
public class ListViewWithCustomerSettingMain extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {


        AnchorPane anchorPane = new AnchorPane();

        ObservableList<User> list = FXCollections.observableArrayList();
        list.add(new User("A", "20", "icons/dlam.png"));
        list.add(new User("B", "22", "icons/lbxx.png"));
        list.add(new User("C", "24", "icons/mla.png"));
        list.add(new User("D", "26", "icons/pkq.png"));

        ListView<User> listView = new ListView<>(list);


        listView.setPrefSize(400, 400);
        AnchorPane.setLeftAnchor(listView, 100.0);
        anchorPane.getChildren().addAll(listView);
        primaryStage.setScene(new Scene(anchorPane));
        primaryStage.setWidth(600);
        primaryStage.setHeight(500);
        primaryStage.show();


        listView.setFixedCellSize(50);
        listView.setEditable(true);

        //自定义cellFactory
        listView.setCellFactory(new Callback<ListView<User>, ListCell<User>>() {
            @Override
            public ListCell<User> call(ListView<User> param) {
                ListCell<User> listCell = new ListCell<User>() {

                    private User currentOperationUser = null;

                    private ListCell<User> currentListCell;

                    /**
                     * {@inheritDoc}
                     */
                    @Override
                    public void startEdit() {
                        super.startEdit();
                        System.out.println("start edit");

                        //更换hbox，让label变成可输出的textfield
                        User selectedItem = param.getSelectionModel().getSelectedItem();

                        currentOperationUser = selectedItem;
                        currentListCell = this;

                        HBox graphic = createHBoxWithTextField(selectedItem);

                        this.setGraphic(graphic);

                        //点击回车
                        TextField nameTf = (TextField) graphic.getChildren().get(1);
                        TextField ageTf = (TextField) graphic.getChildren().get(2);

                        nameTf.requestFocus();

                        EventHandler keyPressedEventHandler = (EventHandler<KeyEvent>) event -> {
                            if(KeyCode.ENTER != event.getCode()){
                                return;
                            }

                            //提交触发动作
                            currentListCell.commitEdit(new User(nameTf.getText(), ageTf.getText(),selectedItem.getPhoto()));
                        };

                        nameTf.setOnKeyPressed(keyPressedEventHandler);
                        ageTf.setOnKeyPressed(keyPressedEventHandler);

                    }

                    /**
                     * {@inheritDoc}
                     */
                    @Override
                    public void cancelEdit() {
                        super.cancelEdit();

                        //更换hbox，让label变成可输出的textfield
                        this.setGraphic(createHBoxWithTextLabel(currentOperationUser));

                    }

                    /**
                     * 更新每行时触发
                     */
                    @Override
                    protected void updateItem(User item, boolean empty) {
                        super.updateItem(item, empty);

                        if(empty){
                            return;
                        }
                        this.setGraphic(createHBoxWithTextLabel(item));

                    }


                    /**
                     * 创建一个hbox--基于输入框
                     * @param user
                     * @return
                     */
                    private HBox createHBoxWithTextField(User user){
                        HBox hBox = new HBox();
                        hBox.setSpacing(20);
                        hBox.setAlignment(Pos.CENTER);

                        ImageView imageView = new ImageView(new Image(user.getPhoto()));
                        imageView.setPreserveRatio(true);
                        imageView.setFitWidth(30);

                        TextField nameTf = new TextField(user.getName());
                        nameTf.setPrefWidth(150);

                        TextField ageTf = new TextField(user.getAge());
                        ageTf.setPrefWidth(150);

                        hBox.getChildren().addAll(imageView,nameTf,ageTf);

                        return hBox;
                    }


                    /**
                     * 创建一个hbox--基于label
                     * @param user
                     * @return
                     */
                    private HBox createHBoxWithTextLabel(User user){
                        HBox hBox = new HBox();
                        hBox.setSpacing(20);
                        hBox.setAlignment(Pos.CENTER);

                        ImageView imageView = new ImageView(new Image(user.getPhoto()));
                        imageView.setPreserveRatio(true);
                        imageView.setFitWidth(30);

                        Label nameLabel = new Label(user.getName());
                        nameLabel.setPrefWidth(150);

                        Label ageLabel = new Label(user.getAge());
                        ageLabel.setPrefWidth(150);

                        hBox.getChildren().addAll(imageView,nameLabel,ageLabel);

                        return hBox;
                    }


                };
                return listCell;
            }
        });




    }






    private class User {
        private String name;
        private String age;
        private String photo;

        public User() {
        }

        public User(String name, String age, String photo) {
            this.name = name;
            this.age = age;
            this.photo = photo;
        }

        public String getName() {
            return name;
        }

        public User setName(String name) {
            this.name = name;
            return this;
        }

        public String getAge() {
            return age;
        }

        public User setAge(String age) {
            this.age = age;
            return this;
        }

        public String getPhoto() {
            return photo;
        }

        public User setPhoto(String photo) {
            this.photo = photo;
            return this;
        }
    }
}
